package com.wutianyi.servlet.codec;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;

import com.wutianyi.utils.NetUtils;
import com.wutianyi.utils.Utils;

public class CodecServlet extends HttpServlet
{

    /**
     * 
     */
    private static final long serialVersionUID = -8164597750309411172L;

    private final String T_V_TO_BASE64 = "tobase64";
    private final String T_V_TO_HEX = "tohex";
    private final String T_V_TO_JS = "toJs";
    private final String T_V_FROM_JS = "fromjs";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        String type = NetUtils.getParameterString(req, "type", "tobase64");
        String value = req.getParameter("value");
        PrintWriter pw = resp.getWriter();
        try
        {

            if (type.equals(T_V_TO_BASE64))
            {
                value = Base64.encodeBase64String(value.getBytes("utf-8"));
            }
            else if (type.equals(T_V_TO_HEX))
            {
                value = Utils.toHexString(value);
            }
            else if(type.equals(T_V_TO_JS))
            {
                value = Utils.encodeUnicode(value);
            }
            else if(type.equals(T_V_FROM_JS))
            {
                value = Utils.decodeUnicode(value);
            }
            else
            {
                value = new String(Base64.decodeBase64(value),"utf-8");
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        pw.print(value);
    }

}
